package com.yan.lesson01;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class TalkReceive implements Runnable{
    DatagramSocket socket = null;
    private int port;
    private String msgFrom;
    public TalkReceive(int port,String msgFrom) throws SocketException {
        this.port = port;
        this.msgFrom = msgFrom;
        socket = new DatagramSocket(port);
    }
    @Override
    public void run() {
        try {
            while (true) {
    //            准备接收包裹
                byte[] container = new byte[1024];
                DatagramPacket packet = new DatagramPacket(container, 0, container.length);
                socket.receive(packet);
                byte[] data = packet.getData();
                String receiveData = new String(data);
                System.out.println(msgFrom+"说:"+receiveData);
                if (receiveData.equals("bye")) {
                    break;
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
//        关闭socket
        socket.close();
    }
}
